package com.jiang.demo.service;

import com.jiang.demo.dao.jpa.UserRepository;
import com.jiang.demo.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;


    public Long save(UserEntity entity){
        UserEntity save = userRepository.save(entity);
        return save.getId();
    }

    public Long delete(Long id){
        UserEntity dbEntity = userRepository.getById(id);
        dbEntity.setIsDelete(true);
        UserEntity save = userRepository.save(dbEntity);
        return save.getId();
    }

    public Long update(UserEntity entity){
        UserEntity dbEntity = userRepository.getById(entity.getId());
        BeanUtils.copyProperties(entity, dbEntity);
        UserEntity save = userRepository.save(dbEntity);
        return save.getId();
    }

    public List<UserEntity> getUserList(){
        return userRepository.findAll();
    }

    public Page<UserEntity> getUserPage(int page, int size){
        Pageable pageable = PageRequest.of(page, size);
        Page<UserEntity> all = userRepository.findAll(pageable);
        return all;
    }

}
